import React from 'react';
import { Modal, Tabs, Form, Row, Col, Input, DatePicker, Steps, Button, message, StepProps } from 'antd';
import moment, { Moment } from 'moment';
import { ASelect } from '@/components/SelfComp';
import { DataItem, FormModalProps } from '@/types/global';
import { TradeTaskConfirmType, TradeTaskCommentType, TradeTaskHandleFormValue } from '@/types/workbench';
import { modalFormItemLayout, maxModalFormItemLayout, getItemValue } from '@/utils/commons';

type TradeTaskConfirmProps<T> = FormModalProps<T> & {
  testerData: DataItem[];
  developerData: DataItem[];
  tradeUndoTaskTypeData: DataItem[];
}

type TradeTaskConfirmFormType = {
  taskName: string;
  taskDate: Moment[];
  developer: string;
  tester: string;
  comment: string;
  /** 任务处理附言 */
  confirmMsg: string;
}

// const { TabPane } = Tabs;
const FormItem = Form.Item;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const dateFormatPattern = 'YYYY-MM-DD';

/**
 * 获取交易任务窗口标题
 */
const getTradeTaskConfirmModalTitle = (funcCode: string, status: string, statusData: DataItem[]) => {
  const title = getItemValue(statusData, status);
  return `交易${funcCode}${title}窗口`;
}

/**
 * 交易分配开发任务相关窗口组件
 */
const TradeTaskConfirmModal: React.FC<TradeTaskConfirmProps<TradeTaskConfirmType>> = (props) => {

  const [form] = Form.useForm<TradeTaskConfirmFormType>();

  const onCancel = () => {
    // 先清除form表单
    form.resetFields();
    const { onHandlerCancel } = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 确认任务
   */
  const approveTaskHandler = () => {
    form.validateFields().then(fieldsValue => {
      // console.info(fieldsValue);
      const { confirmMsg } = fieldsValue;
      tradeTaskHandler(confirmMsg, true);
    }).catch();
  }

  /**
   * 驳回任务
   */
  const rejectTaskHandler = () => {
    form.validateFields().then(fieldsValue => {
      // console.info(fieldsValue);
      const { confirmMsg } = fieldsValue;
      tradeTaskHandler(confirmMsg, false);
    }).catch();
  }

  /**
   * 交易任务处理函数
   * @param confirmMsg 任务处理附言
   * @param agree 确认还是驳回
   */
  const tradeTaskHandler = (confirmMsg: string, agree: boolean) => {
    const values: TradeTaskHandleFormValue = {
      confirmMsg,
      agree
    };
    console.log('Received values of form: ', values);
    const { onHandlerOK } = props;
    if (onHandlerOK) {
      onHandlerOK(values);
    }
  }

  const renderSteps = (data: TradeTaskCommentType[] = []) => {
    const newData = data.map(item => {
      // console.log(item);
      const { userCode, time, comment } = item;
      return {
        title: comment,
        description: `${userCode} ${message} ${time}`
      }
    });
    return newData;
  }

  const CreateForm = (props: TradeTaskConfirmProps<TradeTaskConfirmType>) => {
    const formLayout = 'horizontal';
    const { colon, formData, developerData, testerData } = props;
    const { startDate, endDate } = formData;
    const taskDate = [moment(startDate, dateFormatPattern), moment(endDate, dateFormatPattern)];
    return {
      label: '审批',
      key: 'approveView',
      children: (
        <Form layout={formLayout} form={form}>
          <Row>
            <Col span={24}>
              <FormItem label='任务名称' name='taskName' {...maxModalFormItemLayout} colon={colon}
                initialValue={ formData.taskName }
              >
                <Input disabled />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem label='任务起止时间' name='taskDate' {...modalFormItemLayout} colon={colon}
                initialValue={taskDate}
              >
                <RangePicker format={dateFormatPattern} disabled />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem label='开发人员' name='developer'  {...modalFormItemLayout} colon={colon}
                initialValue={ formData.developer }
              >
                <ASelect dataSource={developerData} disabled />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label='测试人员' name='tester' {...modalFormItemLayout} colon={colon}
                initialValue={ formData.tester }
              >
                <ASelect dataSource={testerData} disabled />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem label='备注/附件CC路径' name='comment' {...maxModalFormItemLayout} colon={colon}
                initialValue={ formData.comment }
              >
                <TextArea disabled/>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem label='附言' name='confirmMsg' {...maxModalFormItemLayout} colon={colon}
                rules={[
                  { max: 100, message: '附言最多允许输入100个字符' },
                  { required: true, message: '附言必输' }
                ]}>
                <TextArea showCount maxLength={100} />
              </FormItem>
            </Col>
          </Row>
        </Form>
      )
    }
  }

  const CreateSteps = (props: TradeTaskConfirmProps<TradeTaskConfirmType>) => {
    const { formData } = props;
    const { hisList } = formData;
    const commentStepItems: StepProps[] = renderSteps(hisList);
    return {
      label: '历史信息',
      key: 'historyView',
      children: (
        hisList && hisList.length > 0 ? <Steps direction='horizontal' size='small' items={commentStepItems} /> : '暂无历史流程信息'
      )
    }
  }

  const { formData, modalWidth, modalVisible, loading, tradeUndoTaskTypeData } = props;
  const { funcCode, status } = formData;
  // 状态为1时，没有驳回按钮
  const title = getTradeTaskConfirmModalTitle(funcCode, status, tradeUndoTaskTypeData);
  // Tabs页签
  const items = [
    CreateForm(props),
    CreateSteps(props)
  ];

  return (
    <Modal
      title={title}
      destroyOnClose
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onCancel={onCancel}
      footer={[
        <React.Fragment>
          <Button key='tradeTaskConfirmModalApprove' type='primary' onClick={approveTaskHandler} loading={loading}>确认</Button>
          { status !== '1' ? <Button key='tradeTaskConfirmModalReject' type='primary' onClick={rejectTaskHandler} loading={loading}>驳回</Button> : null}
          <Button key='tradeTaskConfirmModalCancel' onClick={onCancel}>取消</Button>
        </React.Fragment>
      ]}>
      <Tabs
        defaultActiveKey='approveView'
        items={items}
      />
    </Modal>
  );
}

export default TradeTaskConfirmModal;